package cn.rui.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import cn.rui.common.ResponseBean;
import cn.rui.mapper.UserMapper;
import cn.rui.pojo.User;
import cn.rui.pojo.vo.PageVo;
import cn.rui.pojo.vo.UpdatePassVo;
import cn.rui.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("user")
@Api(tags = "用户模块")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 测试登录，浏览器访问： http://localhost:8081/user/doLogin?username=zhang&password=123456
    @PostMapping("doLogin")
    @ApiOperation(value = "用户登录")
    public ResponseBean doLogin(@RequestBody User user, HttpSession session, Device device) {

        if (device.isMobile ()) {
            log.info ("========请求来源设备是手机！========");
        } else if (device.isTablet ()) {
            log.info ("========请求来源设备是平板！========");
        } else if (device.isNormal ()) {
            log.info ("========请求来源设备是PC！========");
        } else {
            log.info ("========请求来源设备是其他！========");
        }

        return userService.login (user.getUsername (), user.getPassword (), session);
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    // 角色认证：当前会话必须具有指定角色标识才能通过
    @SaCheckRole("super-admin")
    // 登录认证：当前会话必须登录才能通过
    @SaCheckLogin
    // 权限认证：当前会话必须具有指定权限才能通过
    @SaCheckPermission("user-add")
    @RequestMapping("isLogin")
    @ApiIgnore   //忽略文档
    public String isLogin(String username, String password) {
        return "当前会话是否登录：" + StpUtil.isLogin ();
    }

    @GetMapping("logout")
    @ApiOperation(value = "用户退出登录")
    public ResponseBean logout(HttpSession session) {
        session.invalidate ();
        StpUtil.logout ();
        return ResponseBean.success ("注销成功!");
    }


    @PostMapping("findPage")
    @SaCheckLogin
    @ApiOperation(value = "分页查询用户列表")
    public ResponseBean findPage(@RequestBody PageVo pageVo, HttpSession session) {
        return userService.findPage (pageVo, session);
    }


    @PutMapping("/updateRemark/{userId}/{remark}")
    @SaCheckLogin
    @ApiOperation(value = "管理员修改用户备注")
    public ResponseBean updateRemark(@PathVariable("userId") Integer userId, @PathVariable("remark") String remark) {
        return userService.updateRemark (userId, remark);
    }

    @DeleteMapping("/deleteById")
    @SaCheckLogin
    @ApiOperation(value = "根据ID删除用户")
    public ResponseBean deleteById(Integer id) {
        return userService.deleteById (id);
    }


    @PutMapping("updateStatus")
    @ApiOperation(value = "更改用户账号状态")
    @SaCheckLogin
    public ResponseBean updateStatus(Integer id) {
        return userService.updateStatus (id);
    }

    @PutMapping("writeNote")
    @ApiOperation(value = "更改个人便签内容")
    @SaCheckLogin
    public ResponseBean writeNote(String textarea, HttpSession session) {
        return userService.writeNote (textarea, session);
    }

    @PutMapping("updatePass")
    @SaCheckLogin
    @ApiOperation(value = "修改密码")
    public ResponseBean updatePass(@RequestBody UpdatePassVo updatePassVo, HttpSession session) {
        return userService.updatePass (updatePassVo, session);
    }

    @PostMapping("uploadExcel")
    @SaCheckLogin
    @ApiOperation(value = "excel上传用户")
    public ResponseBean uploadExcel(@RequestBody List<User> userList, HttpSession session) {
        System.out.println (userList);
        return null;
        //return userService.uploadExcel(userList,session);
    }

    @Autowired
    private UserMapper userMapper;

    @GetMapping("uploadExcel")
    @SaCheckLogin
    @ApiOperation(value = "excel上传用户")
    public void uploadExcel(HttpServletResponse response) throws IOException {

        List<User> users = userMapper.selectList (null);

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter ();

        writer.getStyleSet ().setAlign (HorizontalAlignment.CENTER, VerticalAlignment.CENTER);

        //设置内容字体
        Font font = writer.createFont ();
        font.setBold (true);
        font.setFontHeightInPoints ((short) 11);
        //font.setColor(Font.COLOR_RED);
        //font.setItalic(true);
        //第二个参数表示是否忽略头部样式
        writer.getStyleSet ().setFont (font, true);

        StyleSet style = writer.getStyleSet ();
        CellStyle cellStyle = style.getHeadCellStyle ();
        Font font2 = writer.createFont ();
        font2.setFontHeightInPoints ((short) 12);
        font2.setBold (true);
        cellStyle.setFont (font2);

        writer.write (users, true);

        //response为HttpServletResponse对象
        response.setContentType ("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码


        response.setHeader ("Content-Disposition", "attachment; filename=" + URLEncoder.encode ("测试", "UTF-8") + ".xlsx");
        //response.setHeader ("Content-Disposition", "attachment;filename=test.xls");
        ServletOutputStream out = response.getOutputStream ();

        writer.flush (out, true);
        // 关闭writer，释放内存
        writer.close ();
        //此处记得关闭输出Servlet流
        IoUtil.close (out);
    }
}